/*
 * Powered By 
 * Since 2010 - 2016
 */

package com.rf.business.control;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.rf.business.model.CardPhoto;
import com.rf.business.model.CardRelease;
import com.rf.business.model.Declaration;
import com.rf.business.service.CardPhotoService;
import com.rf.business.service.CardReleaseService;
import com.rf.sys.frm.BaseController;
import com.rf.sys.model.Department;
import com.rf.sys.model.User;
import com.rf.sys.poi.excel.entity.ExcelTitle;
import com.rf.sys.poi.excel.entity.vo.POIConstants;
import com.rf.sys.service.CommonService;
import com.rf.sys.service.DepartmentService;
import com.rf.sys.utils.ConfigUtils;
import com.rf.sys.utils.DateUtils;
import com.rf.sys.utils.JsonUtils;
import com.rf.sys.utils.PageUtils;
import com.rf.sys.utils.UuidUtil;

@Controller
@RequestMapping("/bus/enterCard")
public class EnterCardController extends BaseController{
	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(EnterCardController.class);
	private static final long serialVersionUID = -120161117110147799L;
	
	@Resource
	private CardReleaseService cardReleaseService;
	@Resource
	private CommonService commonService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private CardPhotoService cardPhotoService;
	/**
	 * 初始化页面信息
	 * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
	 */
	@RequestMapping(value = "index")
    public ModelAndView index (HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView modelAndView = new ModelAndView();
		String url = "/business/enterCard/zjt_list";
		String type = request.getParameter("type");
		if("01".equals(type)){
			url = "/business/enterCard/zjt_list";
		}else if("02".equals(type)){
			url = "/business/enterCard/lxs_list";
		}else if("03".equals(type)){
			url = "/business/enterCard/bj_list";
		}else if("04".equals(type)){
			url = "/business/enterCard/gj_list";
		}else if("05".equals(type)){
			url = "/business/enterCard/port_list";
		}else if("06".equals(type)){
			url = "/business/enterCard/hg_list";
		}else if("07".equals(type)){
			url = "/business/enterCard/nkk_list";
		}
		modelAndView.setViewName(url);
		return modelAndView; 
    }
    
    /**
	 * 搜索页面信息
	 * @param Page,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "query")
    @ResponseBody
    public void query (PageUtils pageUtils, CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	//获取分页、查询参数，进行数据封装
    	Map searchMap = cardReleaseService.getCardReleasePage(cardRelease, pageUtils);
    	super.responsePrint(request, response, JsonUtils.mapToJson(searchMap));
    }
    
    /**
     * 编辑页面初始化
     * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	ModelAndView modelAndView = new ModelAndView();
		String id = request.getParameter("id");
		String carNo = request.getParameter("carNo");
		String type = request.getParameter("type");
		CardRelease cardRelease = new CardRelease();
		if(id != null && !id.equals("")){
			cardRelease = cardReleaseService.getCardReleaseByID(id);
			String entryTime = DateUtils.dateToString(cardRelease.getEntryTime(), ConfigUtils.DATEFORMATER1);
			modelAndView.addObject("cardRelease", cardRelease);
			modelAndView.addObject("entryTime", entryTime);
			if("03".equals(type)){
				modelAndView.addObject("type", "03");
				modelAndView.setViewName("/business/enterCard/edit");
			}else{
				modelAndView.addObject("type", "01");
				modelAndView.setViewName("/business/enterCard/edit");
			}
		}else{
			if(carNo!=null && !carNo.equals("")){
				cardRelease.setCarNo(carNo);
			}
			cardRelease.setSerialNo(commonService.getSerialNo(1));//流水号
			cardRelease.setEntryExitType(ConfigUtils.CLRJ);
			modelAndView.addObject("cardRelease", cardRelease);
	        modelAndView.setViewName("/business/enterCard/add");
		}
        return modelAndView; 
    }
    
    /**
     * 查看页面初始化
     * @param request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "view")
    public ModelAndView view (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	ModelAndView modelAndView = new ModelAndView();
		String id = request.getParameter("id");
		CardRelease cardRelease = new CardRelease();
		if(id != null && !id.equals("")){
			String entryTime = DateUtils.dateToString(cardRelease.getEntryTime(), ConfigUtils.DATEFORMATER1);
			cardRelease = cardReleaseService.getCardReleaseByID(id);	
			modelAndView.addObject("cardRelease", cardRelease);
			modelAndView.addObject("entryTime", entryTime);
	        modelAndView.setViewName("/business/enterCard/view");
		}
        return modelAndView; 
    }
    
    /**
     * 保存数据信息
     * @param CardRelease,request,response
	 * @return ModelAndView
	 * @throws ServletException,IOException
     */
    @RequestMapping(value = "save")
    public void save (HttpServletRequest request, HttpServletResponse response ) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	Date d = new Date();
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
    	String params = request.getParameter("data");
    	String type = request.getParameter("type");
    	String showState = request.getParameter("showState");
    	Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    	CardRelease cardRelease = gson.fromJson(params, CardRelease.class);
		if(cardRelease !=null && cardRelease.getId()!=null && !cardRelease.getId().equals("")){
			//修改
			cardRelease.setLastModifyTime(d);
			cardRelease.setLastModifyUser(user.getId());
			if("03".equals(type)){
				cardRelease.setBorderCheckDate(d);
				cardRelease.setBorderCheckState(ConfigUtils.YFXSTATE);
			}else{
				cardRelease.setIsProcess(ConfigUtils.YCLSTATE);
				cardRelease.setIsMeetCar(ConfigUtils.WJCSTATE);
			}
			cardReleaseService.updateCardRelease(cardRelease);
		}else{
			//新增
			String cardId = UuidUtil.get32UUID();
			cardRelease.setId(cardId);
			cardRelease.setCreateTime(d);
			cardRelease.setCreateUser(user.getId());
			cardRelease.setEntryTime(d);
			cardRelease.setIsProcess(ConfigUtils.YCLSTATE);
			cardRelease.setIsMeetCar(ConfigUtils.WJCSTATE);
			cardReleaseService.addCardRelease(cardRelease);
			//处理图片
			if("2".equals(showState)){
	    		CardPhoto cardPhoto = new CardPhoto();
	    		cardPhoto.setCardId(cardId);
	    		String beforeCardId = "";
	    		List<Map<String, Object>> list = cardPhotoService.getCardPhotoByCarNo(cardRelease.getCarNo());
	    		for(int i=0;i<4;i++){
	    			Map<String, Object> map = list.get(i);
	    			String cid = (String)map.get("CARD_ID");
	    			if(i==0){
	    				beforeCardId = cid;
	    			}
	    			//判断是否同一组数据，防止照片数少于4张
	    			if(beforeCardId.equals(cid)){
	    				String pictype = (String)map.get("PHOTO_TYPE");
		    			if("101501".equals(pictype)){
		    				cardPhoto.setName("正面");
		    			}else if("101502".equals(pictype)){
		    				cardPhoto.setName("侧前");
		    			}else if("101503".equals(pictype)){
		    				cardPhoto.setName("侧后");
		    			}else if("101504".equals(pictype)){
		    				cardPhoto.setName("后面");
		    			}
		    			cardPhoto.setPhotoPath((String)map.get("PHOTO_PATH"));
		    			cardPhoto.setId(UuidUtil.get32UUID());
		    			cardPhoto.setPhotoType(pictype);
		    			cardPhotoService.addCardPhoto(cardPhoto);
	    			}
	    		}
	    	}
		}
    	
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 删除数据信息
     * @param request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "delete")
    @ResponseBody
    public void delete (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String ids = request.getParameter("ids");
    	cardReleaseService.deleteCardRelease(ids);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    /**
     * 查验
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "inspection")
    @ResponseBody
    public void inspection (CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String type = request.getParameter("type");//获取页面type的值，判断是国检、海关、边检
    	if("1".equals(type)){
        	cardRelease.setNationCheckState(ConfigUtils.DFXSTATE);//国检改为待放行    		
    	}else if("2".equals(type)){
    		cardRelease.setCustomCheckState(ConfigUtils.DFXSTATE);//海关改为待放行  
    	}else if("3".equals(type)){
    		cardRelease.setBorderCheckState(ConfigUtils.DFXSTATE);//边检改为待放行  
    	}
    	cardReleaseService.updateCardRelease(cardRelease);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    /**
     * 放行
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "release")
    @ResponseBody
    public void release (CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String type = request.getParameter("type");//获取页面type的值，判断是国检、海关、边检、终检亭
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
    	Date d = new Date();
    	if("1".equals(type)){
    		cardRelease.setNationCheckDate(d);//国检操作时间
        	cardRelease.setNationCheckState(ConfigUtils.YFXSTATE);//放行    		
    	}else if("2".equals(type)){
    		cardRelease.setCustomCheckDate(d);//海关操作时间
        	cardRelease.setCustomCheckState(ConfigUtils.YFXSTATE);//放行    		
    	}else if("3".equals(type)){
    		cardRelease.setBorderCheckState(ConfigUtils.YFXSTATE);//放行 
        	cardRelease.setBorderCheckDate(d);// 边检操作时间
    	}else if("4".equals(type)){
    		cardRelease.setPortCheckDate(d);//口岸放行 
    		cardRelease.setPortCheckState(ConfigUtils.YFXSTATE);
    	}else{
    		cardRelease.setGateCheckDate(d);//南卡口操作时间
        	cardRelease.setGateCheckState(ConfigUtils.YFXSTATE);//放行
    	}
   
    	cardRelease.setLastModifyTime(d);//修改时间
    	cardRelease.setLastModifyUser(user.getId());//最后修改人
    	cardReleaseService.updateCardRelease(cardRelease);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 退车
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "returnCar")
    @ResponseBody
    public void returnCar (CardRelease cardRelease, HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String type = request.getParameter("type");//获取页面type的值
    	//获取当前登陆用户信息
    	Session session = SecurityUtils.getSubject().getSession();
		User user = (User)session.getAttribute("userSession");
		String depid = (String)session.getAttribute("depSessionId");
		Department department = departmentService.getDepartmentByID(depid);
    	Date d = new Date();
    	cardRelease = cardReleaseService.getCardReleaseByID(cardRelease.getId());
    	cardRelease.setBackCarUser(user.getId());//退车人
    	cardRelease.setBackCarTime(d);//退车时间
    	if(department != null){
    		cardRelease.setBackDepName(department.getName());
    	}
    	if("1".equals(type)){
    		cardRelease.setFinalCheckState(ConfigUtils.TCSTATE);//终检亭状态为退回
    		cardRelease.setFinalCheckDate(d);
    	}else if("2".equals(type)){//边检状态为退回
        	cardRelease.setBorderCheckDate(d);//边检操作时间
        	cardRelease.setBorderCheckState(ConfigUtils.TCSTATE);//退车
	    	//生成出境放行卡，各联检部门状态设为放行
	    	CardRelease newCardRelease = new CardRelease();
	    	newCardRelease.setId(UuidUtil.get32UUID());
	    	newCardRelease.setSerialNo(commonService.getSerialNo(1));
	    	newCardRelease.setCarNo(cardRelease.getCarNo());
	    	newCardRelease.setChineseNum(cardRelease.getChineseNum());
	    	newCardRelease.setForeignNum(cardRelease.getForeignNum());
	    	newCardRelease.setTotalNum(cardRelease.getTotalNum());
	    	newCardRelease.setNationality(cardRelease.getNationality());
	    	newCardRelease.setEntryTime(d);
	    	newCardRelease.setCarType(cardRelease.getCarType());
	    	newCardRelease.setEntryExitType(ConfigUtils.CLCJ);
	    	newCardRelease.setIsProcess("");
	    	newCardRelease.setBorderCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setBorderCheckDate(d);
	    	newCardRelease.setNationCheckDate(d);
	    	newCardRelease.setNationCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setCustomCheckDate(d);
	    	newCardRelease.setCustomCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setGateCheckDate(d);
	    	newCardRelease.setGateCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setCreateTime(d);
	    	newCardRelease.setCreateUser(user.getId());
    		newCardRelease.setOpeCheckDate(d);
    		newCardRelease.setOperationState(ConfigUtils.YFXSTATE);
    		newCardRelease.setFinalCheckState(ConfigUtils.DFXSTATE);
	    	cardReleaseService.addCardRelease(newCardRelease);
    	}else{//海关状态为退回
        	cardRelease.setCustomCheckDate(d);//海关操作时间
        	cardRelease.setCustomCheckState(ConfigUtils.TCSTATE);//退车
	    	//生成出境放行卡，各联检部门状态设为放行
	    	CardRelease newCardRelease = new CardRelease();
	    	newCardRelease.setId(UuidUtil.get32UUID());
	    	newCardRelease.setSerialNo(commonService.getSerialNo(1));
	    	newCardRelease.setCarNo(cardRelease.getCarNo());
	    	newCardRelease.setChineseNum(cardRelease.getChineseNum());
	    	newCardRelease.setForeignNum(cardRelease.getForeignNum());
	    	newCardRelease.setTotalNum(cardRelease.getTotalNum());
	    	newCardRelease.setNationality(cardRelease.getNationality());
	    	newCardRelease.setEntryTime(d);
	    	newCardRelease.setCarType(cardRelease.getCarType());
	    	newCardRelease.setEntryExitType(ConfigUtils.CLCJ);
	    	newCardRelease.setIsProcess(ConfigUtils.YCLSTATE);
	    	newCardRelease.setBorderCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setBorderCheckDate(d);
	    	newCardRelease.setNationCheckDate(d);
	    	newCardRelease.setNationCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setCustomCheckDate(d);
	    	newCardRelease.setCustomCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setGateCheckDate(d);
	    	newCardRelease.setGateCheckState(ConfigUtils.YFXSTATE);
	    	newCardRelease.setCreateTime(d);
	    	newCardRelease.setCreateUser(user.getId());
    		newCardRelease.setOpeCheckDate(d);
    		newCardRelease.setOperationState(ConfigUtils.YFXSTATE);
    		newCardRelease.setFinalCheckState(ConfigUtils.DFXSTATE);
	    	cardReleaseService.addCardRelease(newCardRelease);
    	}
    	cardRelease.setLastModifyTime(d);//最后修改时间
    	cardRelease.setLastModifyUser(user.getId());//最后修改人
    	cardReleaseService.updateCardRelease(cardRelease);
		returnObj.element("message", "success");//成功
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 加载车辆图片
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "loadPic")
    @ResponseBody
    public void loadPic (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String carNo = request.getParameter("carNo");
    	List<Map<String, Object>> list = cardPhotoService.getCardPhotoByCarNo(carNo);
    	if(list.size()>0){
    		returnObj.element("message", "success");//成功
    		for(int i=0;i<4;i++){
    			Map<String, Object> map = list.get(i);
    			String type = (String)map.get("PHOTO_TYPE");
    			if("101501".equals(type)){
    				returnObj.element("zm", map.get("PHOTO_PATH"));//正面
    			}else if("101502".equals(type)){
    				returnObj.element("cq", map.get("PHOTO_PATH"));//测前
    			}else if("101503".equals(type)){
    				returnObj.element("ch", map.get("PHOTO_PATH"));//侧后
    			}else if("101504".equals(type)){
    				returnObj.element("hm", map.get("PHOTO_PATH"));//后面
    			}
    		}
    	}else{
    		returnObj.element("message", "error");//未查询到
    	}
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * 加载车辆通关状态
     * @param cardRelease,request,response
	 * @return JSON
	 * @throws ServletException,IOException
	 */
    @RequestMapping(value = "loadReleaseInfo")
    @ResponseBody
    public void loadReleaseInfo (HttpServletRequest request, HttpServletResponse response) throws Exception{
    	JSONObject returnObj = new JSONObject();
    	String carNo = request.getParameter("carNo");
    	if(carNo != null && !carNo.equals("")){
    		CardRelease cardRelease = cardReleaseService.getCardReleaseByCarNo(carNo);	
    		if(cardRelease != null && !cardRelease.equals("") && cardRelease.getId() != null){
    			returnObj.element("clzt", cardRelease.getIsProcess());//处理状态
    			returnObj.element("jczt", cardRelease.getIsMeetCar());//接车状态
    			returnObj.element("bjzt", cardRelease.getBorderCheckState());//边检状态
    			returnObj.element("gjzt", cardRelease.getNationCheckState());//国检状态
    			returnObj.element("kazt", cardRelease.getPortCheckState());//口岸状态
    			returnObj.element("hgzt", cardRelease.getCustomCheckState());//海关状态
    			returnObj.element("nkkzt", cardRelease.getGateCheckState());//南卡口状态
    			returnObj.element("zjtzt", cardRelease.getFinalCheckState());//终检亭状态
//    		returnObj.element("rjtime", "success");//入境时间
//    		returnObj.element("jctime", "success");//接车时间
//    		returnObj.element("hgtime", "success");//海关放行时间
//    		returnObj.element("gjtime", "success");//国检放行时间
//    		returnObj.element("bjtime", "success");//边检放行时间
//    		returnObj.element("katime", "success");//口岸放行时间
//    		returnObj.element("nkktime", "success");//南卡口放行时间
    			returnObj.element("ygzt", cardRelease.getOperationState());//运管状态
//    		returnObj.element("ygtime", "success");//运管时间
    			returnObj.element("crjtype", cardRelease.getEntryExitType());//出入境类型
    			returnObj.element("message", "success");//成功
    		}else{
    			returnObj.element("message", "error");//未查询到
    		}
    		
    	}else{
    		returnObj.element("message", "error1");//未查询到
    	}
		super.responseJson(request, response, returnObj.toString());
    }
    
    /**
     * @author dehuisun
     * 
	 * 导出单页签excel
	 * @param request
	 * @param response
     * @throws Exception 
	 */
	@RequestMapping(value = "exportXls")
	public String exportXls(HttpServletRequest request, HttpServletResponse response,ModelMap map) throws Exception {
		CardRelease cardRelease=new CardRelease();
		Map rmap=super.getInfos(request,cardRelease);
		cardRelease=(CardRelease) rmap.get("data");//查询参数
		PageUtils pageUtils=(PageUtils) rmap.get("pdata");//分页参数
		//获取分页、查询参数，进行数据封装
    	Map<?, ?> searchMap = cardReleaseService.getCardReleasePage(cardRelease, pageUtils);
    	if(searchMap!=null){
    		List<?> list=(List<?>) searchMap.get("rows");
    		map.put(POIConstants.FILE_NAME,"放行卡信息导出");
            map.put(POIConstants.CLASS,CardRelease.class);
            map.put(POIConstants.EXCEL_TITLE,new ExcelTitle(null, null,"附表"));
            map.put(POIConstants.DATA_LIST,list);
    	}
    	return POIConstants.EXCEL_VIEW;
	}
}


